﻿@page "/ClientList"

@namespace SageKing.Studio.Pages.ClientList

@implements IMenuTab<SysMenu, long>
@implements IReuseTabsPage

<PageTitle>@TabTitle</PageTitle>

@inject SysMenuService _sysMenuService
@inject ISageKingPackagesService dataService

@code {
	class PushModel
	{
		[Required]
		public string Message { get; set; }

		[RequiredList]
		public IEnumerable<string> ConnectIds { get; set; }
	}
}

@if (dic == null)
{
	<Spin size="SpinSize.Large" Tip="Loading..." />
}
else
{
	<Table @ref="table" TItem="ClientConnectionInfo<IConnectionContext>"
		   DataSource="@dic" RowKey="a=>a.ConnectionId"
		   OnRowClick="OnRowClick" @bind-SelectedRows="@selectedRows"
		   Size="TableSize.Small" Loading="tableLoading" Resizable Bordered EnableVirtualization
		   Class="main-table" ScrollY="@BrowserConsts.ScrollYTable" PageSize="20">

		<TitleTemplate>
			<Form @ref="form"
				  Model="@model"
				  ValidateOnChange="true">
				<Space>
					<SpaceItem>
						<Select Mode="SelectMode.Multiple"
								Placeholder="请选择客户端"
								@bind-Values="@model.ConnectIds"
								DataSource="@ConnectIdsSelect"
								LabelName="@nameof(KeyValue<string,string>.Value)"
								ValueName="@nameof(KeyValue<string,string>.Key)"
								Style="min-width:150px; width: auto;"
								TItemValue="string"
								TItem="KeyValue<string,string>"
								OnSelectedItemsChanged="OnSelectedItemsChangedHandler"
								EnableSearch
								AllowClear>
						</Select>
					</SpaceItem>
					<SpaceItem>
						<Input @ref=inputMessageRef Placeholder="输入推送内容" @bind-Value="model.Message" AllowClear="true" ShowCount MaxLength="200" />
					</SpaceItem>
					<SpaceItem>
						<Button Type="@ButtonType.Primary" @onclick="Push" Loading="@loading">推送</Button>
					</SpaceItem>
					<SpaceItem>
						<Button Type="@ButtonType.Primary" Icon="@IconType.Outline.Reload" OnClick="()=>ReSet()">重置</Button>
					</SpaceItem>
					<SpaceItem>
						<label class="validation-message">@Notice</label>
					</SpaceItem>
				</Space>
			</Form>
		</TitleTemplate>

		<ColumnDefinitions>
			<Selection Key="@context.ConnectionId" Type="@selectionType"></Selection>

			<PropertyColumn Property="c=>c.ClientId" Title="ClientId"></PropertyColumn>
			<PropertyColumn Property="c=>c.ClientType" Title="ClientType"></PropertyColumn>
			<PropertyColumn Property="c=>c.ClientTypeDesc" Title="Desc"></PropertyColumn>
			<PropertyColumn Property="c=>c.LocalAddress" Title="LocalAddress"></PropertyColumn>
			<PropertyColumn Property="c=>c.RemoteAddress" Title="RemoteAddress"></PropertyColumn>
			<PropertyColumn Property="c=>c.IceProxyId" Title="IceProxyId"></PropertyColumn>
			<PropertyColumn Property="c=>c.LoginDateTime" Title="LoginDateTime"></PropertyColumn>
			<PropertyColumn Property="c=>c.ConnectionId" Title="ConnectionId"></PropertyColumn>

		</ColumnDefinitions>

		<PaginationTemplate>
			<Pagination ShowTotal="showTotal" Class="@(context.PaginationClass + " my-custom-pagination")"
						Total="context.Total"
						PageSize="context.PageSize"
						Current="context.PageIndex"
						ShowSizeChanger
						ShowQuickJumper />
		</PaginationTemplate>
	</Table>

}

@code {

	bool loading;
	static bool IsfirstRender = false;

	PushModel model = new PushModel();
	AntDesign.Form<PushModel> form;

	string Notice = string.Empty;
	AntDesign.Input<string> inputMessageRef;


	//table
	ITable table;
	bool tableLoading;
	SelectionType selectionType = SelectionType.Checkbox;
	RenderFragment<PaginationTotalContext> showTotal = ctx => @<div class="showTotal">Total: <b>@ctx.Total</b></div>;

	IEnumerable<ClientConnectionInfo<IConnectionContext>> dic;
	IEnumerable<ClientConnectionInfo<IConnectionContext>> selectedRows;
	IEnumerable<KeyValue<string, string>> ConnectIdsSelect;

	#region init
	#region menu
	public IMenuTab<SysMenu, long> MeTab { get { return this; } }

	public IBaseServiceCache<SysMenu, long> MenuService
	{ get { return _sysMenuService; } }

	[SupplyParameterFromQuery(Name = "menuid")]
	public long menuid { get; set; }

	[Parameter]
	public string TabTitle { get; set; } = "客户端管理中心";

	[Parameter]
	public string TabIcon { get; set; } = "home";

	public RenderFragment GetPageTitle() =>
	@<div>
		<Icon Type="@TabIcon" /> @TabTitle
	</div>
	;
	#endregion

	[CascadingParameter]
	public Error? Error { get; set; }

	protected override async Task OnInitializedAsync()
	{
		try
		{
			await InitSelectData();
			await MeTab.InitTabTitle();
		}
		catch (Exception ex)
		{
			Error?.ProcessError(ex);
		}
	}

	async Task InitSelectData()
	{
		dic = dataService.GetClientConnectionDic.Values.ToList();
		selectedRows = new List<ClientConnectionInfo<IConnectionContext>>();
		ConnectIdsSelect = dic.Select(a => new KeyValue<string, string>(a.ConnectionId, $"{a.ClientId}:{a.ClientTypeDesc}"));
	}
	#endregion

	void ReSet()
	{
		model = new PushModel();
	}

	private void OnSelectedItemsChangedHandler(IEnumerable<KeyValue<string, string>> values)
	{
		if (values != null)
		{
			table.SetSelection(values.Select(a => a.Key).Distinct().ToArray());
		}
		else
		{
			table.SetSelection(null);
		}
	}

	private async void Push()
	{

		if (!form.Validate())
		{
			if (!(model.Message.IsNotNullOrWhiteSpace() && selectedRows.Count() > 0))
			{
				return;
			}
		};

		Notice = $"开始推送:{selectedRows.Count()}个客户端";

		loading = true;

		foreach (var item in selectedRows)
		{
			var result = await dataService.PushMsgAsync(item.ConnectionId, model.Message.GetDataStreamBody().ToArray(), $"Test:Push");
		}

		loading = false;

		model.Message = string.Empty;
		Notice = $"推送完成:{selectedRows.Count()}个。{DateTime.Now}";

		await inputMessageRef.Focus();

		StateHasChanged();
	}

	void OnRowClick(RowData<ClientConnectionInfo<IConnectionContext>> row)
	{
		if (selectedRows.Where(a => a.ConnectionId == row.Data.ConnectionId).Any())
		{
			RemoveSelection(row.Data.ConnectionId);
		}
		else
		{
			AddSelection(row.Data.ConnectionId);
		}
	}

	void RemoveSelection(string key)
	{
		var selected = selectedRows.Where(x => x.ConnectionId != key).ToList();
		table.SetSelection(selected.Select(x => x.ConnectionId).ToArray());
	}

	void AddSelection(string key)
	{
		var currlist = selectedRows.Select(a => a.ConnectionId).ToList();
		currlist.Add(key);
		table.SetSelection(currlist.ToArray());
	}
}
